package com.moleq.device;

import java.util.Locale;

import jp.co.casio.caios.framework.device.DeviceCommon;
import jp.co.casio.caios.framework.device.LineDisplay;

public class CasioDisplayScreen implements ILineScreen {

	// 设备状态
	private LocalDevice mDeviceState;
	private LineDisplay mLineDisplay;
	private boolean mIsConnected = false;

	public CasioDisplayScreen() {
		mDeviceState = LocalDevice.CLOSE_STATE;
	}

	private void display(String line1, String line2) {
//		String sLanguage = Locale.getDefault().getLanguage();
		String sCountry = Locale.getDefault().getCountry();
		// set the string based on the locale
		byte[] dsp_l1 = DeviceUtil.getEncodedStringByCountry(line1, sCountry);
		byte[] dsp_l2 = DeviceUtil.getEncodedStringByCountry(line2, sCountry);

		mLineDisplay.setText(dsp_l1, dsp_l2, LineDisplay.LCD_CONTROL_NORMAL);
		
	}

	@Override
	public void displayLine(String strContent) {
		if (strContent.equals(""))
			return;

		
		int len = strContent.length();
		int pos = strContent.indexOf("\n");
		if(pos != -1){
			this.display(strContent.substring(0, pos),
					strContent.substring(pos + 1, len ));
		}else{
			if (len > 28) {
				this.display(strContent.substring(0, 28),
						strContent.substring(29, len - 1));
			} else {
				this.display(strContent, "");
			}
		}
		
		

	}

	@Override
	public LocalDevice getState() {
		return this.mDeviceState;
	}

	@Override
	public int isReady() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void onDisconnect() {
		if (this.mDeviceState == LocalDevice.OPEN_STATE) {
			mLineDisplay.clear();
			mLineDisplay.setBacklight(LineDisplay.LCD_BACKLIGHT_OFF);
			mLineDisplay.close();
			this.mDeviceState = LocalDevice.CLOSE_STATE;
			mIsConnected = false;
		}
	}

	@Override
	public void onConnect() {
		mLineDisplay = new LineDisplay();
		int response = 0;
		response = mLineDisplay.open(DeviceCommon.DEVICE_MODE_COMMON, null);
		if (response != 0) {
			this.mDeviceState = LocalDevice.CLOSE_STATE;
			return;
		}
		mLineDisplay.setCurrentCodepage();
		mLineDisplay.setBacklight(LineDisplay.LCD_BACKLIGHT_WHITE);
		this.mDeviceState = LocalDevice.OPEN_STATE;
		mIsConnected = true;
	}

	@Override
	public void setCallbackEvent(IDeviceEvent impl) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setComPort(int comPort) {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendCmd(String strCommand) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onClearBuffer() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean isConnected() {
		// TODO Auto-generated method stub
		return mIsConnected ;
	}

}
